package com.fcscs.cservice.domain.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fcscs.cservice.common.CServiceCommonEnums.EditableCategoryEnum;
import com.fcscs.cservice.common.CServiceCommonEnums.EditableFieldEnum;
import com.fcscs.cservice.common.CServiceConstants;
import com.fcscs.cservice.domain.FieldEditability;

public class EditabilityConf implements Serializable {

	private static final long serialVersionUID = -116650723677946671L;

	private Map<EditableCategoryEnum, List<FieldEditability>> editableMap = new HashMap<EditableCategoryEnum, List<FieldEditability>>();

	public void setEditableMap(Map<EditableCategoryEnum, List<FieldEditability>> editableMap) {
		this.editableMap = editableMap;
	}

	public Map<EditableCategoryEnum, List<FieldEditability>> getEditableMap() {
		return editableMap;
	}

	public void setEditableFieldList(EditableCategoryEnum category, List<FieldEditability> editableFieldList) {
		Collections.sort(editableFieldList, FieldEditability.getComparator());
		editableMap.put(category, editableFieldList);
	}

	public List<FieldEditability> getEditableFieldList(EditableCategoryEnum category) {
		return editableMap.get(category);
	}

	public FieldEditability getField(EditableCategoryEnum category, EditableFieldEnum field) {
		List<FieldEditability> editableFieldList = editableMap.get(category);
		if (editableFieldList == null) {
			return null;
		}
		int index = FieldEditability.binarySearch(editableFieldList, category, field);
		if (index >= 0) {
			return editableFieldList.get(index);
		} else {
			return null;
		}
	}

	public boolean isEditable(EditableCategoryEnum category, EditableFieldEnum field) {
		FieldEditability fe = getField(category, field);
		return fe != null ? fe.getEditable() : CServiceConstants.DEFAULT_EDITABILITY;
	}

	public List<FieldEditabilityView> toFieldEditViewList() {
		List<FieldEditabilityView> list = new ArrayList<FieldEditabilityView>();
		for (List<FieldEditability> tempList : editableMap.values()) {
			for (FieldEditability fe : tempList) {
				FieldEditabilityView fev = new FieldEditabilityView();
				fev.setModule(fe.getCategory());
				fev.setField(fe.getField());
				fev.setEditable(fe.getEditable());
				list.add(fev);
			}
		}
		return list;
	}
}
